/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.HttpKit;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.modules.web.entity.WxAgentsCommissionRecord;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.task.TimersTask;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxAgentsRecording;
import com.jeeplus.modules.web.mapper.WxAgentsRecordingMapper;
import com.jeeplus.modules.web.mapper.YjEquipmentMapper;

/**
 * 分销商收入记录Service
 * @author rongjie
 * @version 2017-09-02
 */
@Service
@Transactional(readOnly = true)
public class WxAgentsRecordingService extends CrudService<WxAgentsRecordingMapper, WxAgentsRecording> {
	public static Logger logs = LoggerFactory.getLogger(TimersTask.class);

	@Autowired
	private YjEquipmentMapper yjEquipmentMapper;
	@Autowired
	private WxAgentsRecordingMapper wxAgentsRecordingMapper;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;
	private static String payUrl = Global.getConfig("payUrl");// 应用ID
	@Autowired
	private WxAgentsCommissionRecordService wxAgentsCommissionRecordService;



	public WxAgentsRecording get(String id) {
		return super.get(id);
	}

	/**
	 * 根据agentId和orderNumber获取单条分佣记录
	 * @param agentId
	 * @param orderNumber
	 * @return
	 */
	public WxAgentsRecording getRecordingByAgentIdAndOrderNumber(String agentId, String orderNumber) {
		return wxAgentsRecordingMapper.getRecordingByAgentIdAndOrderNumber(agentId, orderNumber);
	}

	public List<WxAgentsRecording> findList(WxAgentsRecording wxAgentsRecording) {
		return super.findList(wxAgentsRecording);
	}

	public Page<WxAgentsRecording> findPage(Page<WxAgentsRecording> page, WxAgentsRecording wxAgentsRecording) {
		return super.findPage(page, wxAgentsRecording);
	}

	@Transactional(readOnly = false)
	public void save(WxAgentsRecording wxAgentsRecording) {
		super.save(wxAgentsRecording);
	}

	@Transactional(readOnly = false)
	public void delete(WxAgentsRecording wxAgentsRecording) {
		super.delete(wxAgentsRecording);
	}

	/**
	 * 设置代理商佣金和新增代理商返佣记录
	 * @param wxAgents  代理商
	 * @param money     可计入分佣的金额
	 * @param orderMoney 定单金额（与开机定单的金额不是一回事，比如中途关机的话，消费多少则该金额是多少）
	 * @param orderNumber 产生分佣的消费定单号
	 * @param mac  设备
	 */
	@Transactional(readOnly = false)
	public WxAgentsRecording saveWxAgentsRecording(WxAgents wxAgents, double money, double orderMoney, String orderNumber, String mac,Integer type){
		money = new BigDecimal(money / 100).multiply(wxAgents.getProportion()).doubleValue();
//		money = money == 0 ? 0.01 : money;
		yjEquipmentMapper.setAgents(money, orderNumber, wxAgents.getId());
		WxAgentsRecording wxAgentsRecording = new WxAgentsRecording();
		wxAgentsRecording.setAgents(wxAgents);
		wxAgentsRecording.setMoney(money);
		wxAgentsRecording.setOrderMoney(orderMoney);
		wxAgentsRecording.setNumber(orderNumber);
		wxAgentsRecording.setEquipment(mac);
		wxAgentsRecording.setType(type);
		wxAgentsRecordingMapper.insert(wxAgentsRecording);
		return wxAgentsRecording;
	}

	/**
	 * 为代理商增加分佣和分佣记录
	 *
	 * @param mac
	 * @param number
	 * @param orderMoney
	 * @param money
	 */
	@Transactional(readOnly = false)
	public void saveAgentRecordingForAgents(String mac, String number, Double orderMoney, Double money) {

		WxAgents wxAgents = yjEquipmentMapper.getAgents(mac);

		// 分佣计算方式：当前代理商及其所有父级代理商都需要进行分佣，
		// 如A总代理B一级代理下的C代理商所经营的机器盈利，此时结算分佣，ABC都将有相应的分佣

		// 最顶层代理商的parent_id为-1，当到达最顶层之后，
		JSONObject config = new JSONObject();
		if(wxAgents.getRatioId()!=null){
			JSONArray array = JSONObject.parseArray(wxAgents.getCommissionRatio().getConfig());
			WxAgents finalWxAgents = wxAgents;
			config = (JSONObject)array.stream().filter(r -> ((JSONObject) r).getInteger("deviceType").equals(finalWxAgents.getDeviceType())).findFirst().orElseGet(JSONObject::new);
		}
		while (wxAgents != null) {
			// 保存当前代理商的分佣
			WxAgentsRecording recording = getRecordingByAgentIdAndOrderNumber(wxAgents.getId(),
					number);
			// 记录分佣之前，先判断代理商是否已经获取该订单的分佣，避免硬件发送多次响应消息时，重复记录分佣数据
			if (null != recording) {
				logs.info(String.format("ID为%s的代理商已存在订单号为%s的分佣记录", wxAgents.getId(), number));
			} else {
				// 保存当前代理商的分佣
				try {
					BigDecimal proportion = config.getBigDecimal(wxAgents.getAgentLevel() + "");

					if(proportion!=null){
						wxAgents.setProportion(proportion);
					}else{
						wxAgents.setProportion(BigDecimal.ZERO);
					}

					Integer type = config.containsKey("type") ? config.getInteger("type"):-1;

					logs.info(String.format("为ID为%s的代理商增加分佣数据", wxAgents.getId()));
					WxAgentsRecording wxAgentsRecording = saveWxAgentsRecording(wxAgents, money, orderMoney, number, mac, type);
					saveAgentRecording(wxAgentsRecording);

				} catch (Exception e) {
					logs.error("增加分佣数据失败，代理商ID为：" + wxAgents.getId());
					logs.error("异常消息：" + e.getMessage());
					e.printStackTrace();
				}
			}

			// 通过parentId查询父级代理商，如果parentId为null，则转换为null。如果直接调用String.valueOf(wxAgents.getParentId())，转换成的是"null"字符串
			// 如果当前agent已经是顶层，那么将查不到agent数据，循环终止
			// 当代理商层级数据不完整时，此方法亦可行
			String parentId = wxAgents.getParentId() == null ? null : String.valueOf(wxAgents.getParentId());
			wxAgents = wxAgentsMapper.get(parentId);
		}
	}

	@Transactional(readOnly = false)
	public void saveAgentRecording(WxAgentsRecording wxAgentsRecording) {
		if(wxAgentsRecording.getType().equals(1)){
			WxAgentsCommissionRecord wxAgentsCommissionRecord = new WxAgentsCommissionRecord();
			wxAgentsCommissionRecord.setAgents(wxAgentsRecording.getAgents());
			wxAgentsCommissionRecord.setMoney(new BigDecimal(wxAgentsRecording.getMoney()));
			wxAgentsCommissionRecord.setOrdermoney(new BigDecimal(wxAgentsRecording.getOrderMoney()));
			wxAgentsCommissionRecord.setRemarks("分佣");
			wxAgentsCommissionRecordService.save(wxAgentsCommissionRecord);
			//更新代理商佣金
			wxAgentsMapper.updateKtxMoney(wxAgentsRecording.getMoney(),wxAgentsRecording.getAgents().getId());
		}else if(wxAgentsRecording.getType().equals(0)){
			//更新代理商佣金
			wxAgentsMapper.updateMoney(wxAgentsRecording.getMoney(),wxAgentsRecording.getAgents().getId());
		}
	}

}
